package com.candy.blog.aspect;

import com.sun.org.apache.regexp.internal.RE;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * @version 1.0
 * @author: 南风
 * @description 使用AOP进行日志处理
 * @date: 2021/11/25 13:28
 */
@Aspect
@Component // 开启组件扫描
public class LogAspect {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    // 定义一个切面

    /**
     * execution 表达式定义拦截哪些类
     * 拦截web包下的所有web控制器
     */
    @Pointcut("execution(* com.candy.blog.web.*.*(..))")
    public void log() {

    }

    /**
     * 在切面执行之前执行一些操作
     *
     * @Before("log()") 需要在注解中将切面传进来
     */
    @Before("log()")
    public void doBefore(JoinPoint joinPoint) {
        // 在方法中获取请求上下文
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        // 获取请求request
        HttpServletRequest request = attributes.getRequest();
        String url = request.getRequestURL().toString();
        String ip = request.getRemoteAddr();
        String classMethod = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        RequestLog requestLog = new RequestLog(url, ip, classMethod, args);
        logger.info("Request :{}", requestLog);

    }

    @After("log()")
    public void doAfter() {
       // logger.info("-------------------doAfter-------------------");
    }

    // 记录各个方法返回的内容
    @AfterReturning(returning = "result", pointcut = "log()")
    public void doAfterReturn(Object result) {
        logger.info("Result : {}", result);
    }

    // 定义一个内部类
    private class RequestLog {
        private String url; // 访问者url
        private String ip;  // 访问者ip
        private String classMethod; // 调用方法
        private Object[] args; // 请求的参数

        // 全参构造
        public RequestLog(String url, String ip, String classMethod, Object[] args) {
            this.url = url;
            this.ip = ip;
            this.classMethod = classMethod;
            this.args = args;
        }

        @Override
        public String toString() {
            return "{" +
                    "url='" + url + '\'' +
                    ", ip='" + ip + '\'' +
                    ", classMethod='" + classMethod + '\'' +
                    ", args=" + Arrays.toString(args) +
                    '}';
        }
    }
}
